<template>
  <div class="container">
    <a-tabs
      v-model:activeKey="activeKey"
      :tabBarStyle="{ padding: '0 2%', margin: '0' }"
      @change="findTaskByTab(current)"
    >
      <template #rightExtra>
        <a-button type="primary" @click="handleOpenCreateTaskModal">
          <template #icon> <PlusOutlined /> </template>新建任务
        </a-button>
      </template>
      <a-tab-pane :key="null" tab="全部任务"></a-tab-pane>
      <a-tab-pane :key="1" tab="我负责的任务"></a-tab-pane>
      <a-tab-pane :key="2" tab="我创建的任务"></a-tab-pane>
    </a-tabs>

    <div class="filter">
      <!-- 筛选栏 -->
      <a-form
        ref="formRef"
        :model="formState"
        layout="inline"
        :label-col="{ style: { width: '80px' } }"
        AutoComplete="off"
      >
        <a-form-item label="任务类型" name="taskType">
          <a-select
            ref="select"
            v-model:value="formState.taskType"
            style="width: 100px"
            @change="findTaskByTab(1)"
            placeholder="筛选类型"
            :options="typeOptions"
            allow-clear
          ></a-select>
        </a-form-item>
        <a-form-item label="所属课程" name="course" v-if="type == 2">
          <a-select
            ref="select"
            v-model:value="formState.course"
            style="width: 200px"
            @change="findTaskByTab(1)"
            :fieldNames="{ label: 'courseName', value: 'courseId' }"
            allow-clear
            placeholder="筛选课程"
            :options="courseList"
          ></a-select>
        </a-form-item>
        <a-form-item name="taskName">
          <a-input-search
            v-model:value="formState.taskName"
            placeholder="输入任务名称"
            allow-clear
            enter-button
            @search="findTaskByTab(1)"
            @press-enter="findTaskByTab(1)"
          />
        </a-form-item>
      </a-form>
    </div>

    <a-table
      :columns="columns"
      :bordered="true"
      :data-source="data"
      :pagination="false"
      row-key="key"
      :loading="loading"
      :scroll="{ y: '65vh' }"
      :customRow="
        (record) => {
          return {
            onclick: (event) => {
              showDrawer(record);
            }
          };
        }
      "
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'taskName'">
          <a>{{ text }}</a>
        </template>
        <template v-else-if="column.dataIndex === 'taskType'">
          <span v-if="text == 0"><a-tag color="blue">课程任务</a-tag></span>
          <span v-else-if="text == 1"><a-tag color="green">需求任务</a-tag></span>
          <span v-else-if="text == 2"><a-tag color="cyan">开发任务</a-tag></span>
          <span v-else-if="text == 3"><a-tag color="yellow">测试任务</a-tag></span>
          <span v-else-if="text == 4"><a-tag color="orange">缺陷任务</a-tag></span>
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <a-button>分配</a-button>
        </template>
      </template>
    </a-table>

    <a-pagination
      class="pagination-container"
      v-model:current="current"
      v-model:page-size="pageSizeRef"
      :total="total"
      show-size-changer
      @change="findTaskByTab(current)"
    />
  </div>

  <TaskDrawer
    v-model:model-visible="openDrawer"
    :task-id="taskId"
    :course-list="courseList"
    @confirm="findTaskByTab(current)"
  />
  <CreateTaskModal
    v-model:model-visible="openCreateTaskModal"
    :course-list="courseList"
    @confirm="findTaskByTab(current)"
  />
</template>
<script lang="ts" setup>
import type { TableColumnsType } from 'ant-design-vue';
import CreateTaskModal from './CreateTaskModal.vue';
import TaskDrawer from './taskDrawer.vue';
import TaskDao from '@/daos/task_dao';
import CourseDao from '@/daos/course_dao';
import { useStore } from 'vuex';

const store = useStore();
const taskDao = new TaskDao();
const courseDao = new CourseDao();
//判断是否未为项目式教学项目
const type = store.getters.projectType;
//分页参数
const current = ref(1);
const pageSizeRef = ref(10);
const total = ref();
//任务抽屉参数
const openDrawer = ref<boolean>(false);
const openCreateTaskModal = ref<boolean>(false);
//项目和任务ID
const projectId = store.getters.projectId;
const taskId = ref();
//课程列表
const activeKey = ref(null);
const courseList = ref(store.getters.courseList || []);
//表格数据
const formRef = ref();
const loading = ref(false);
const data = ref([]);
//筛选条件项
const formState = reactive({
  taskName: undefined,
  taskType: null,
  course: undefined,
  creatorId: undefined,
  userId: undefined
});
const typeOptions = ref([
  {
    value: 1,
    label: '需求任务'
  },
  {
    value: 2,
    label: '开发任务'
  },
  {
    value: 3,
    label: '测试任务'
  },
  {
    value: 4,
    label: '缺陷任务'
  },
  {
    value: 0,
    label: '课程任务',
    disabled: type != 2
  }
]);
const showDrawer = (record) => {
  taskId.value = record.taskId;
  openDrawer.value = true;
};

const columns: TableColumnsType = [
  { title: '任务名称', dataIndex: 'taskName', fixed: 'left', width: 300 },
  { title: '任务类型', dataIndex: 'taskType', width: 150, align: 'center' },
  { title: '分配数量', dataIndex: 'assignmentCount', width: 150, align: 'center' },
  { title: '创建时间', dataIndex: 'createTime', width: 300, align: 'center' }
];

onMounted(() => {
  findTask(1);
  fetchCourseList();
});

const findTask = (current) => {
  loading.value = true;
  taskDao
    .findTasksByProjectId(
      projectId,
      formState.taskName,
      formState.taskType,
      formState.course,
      formState.creatorId,
      formState.userId,
      current,
      pageSizeRef.value
    )
    .then((result) => {
      data.value = result.data.data.rows;
      total.value = result.data.data.totalCount;
      loading.value = false;
    })
    .catch((error) => {
      console.error('获取任务列表失败 findTasksByProjectId', error);
      loading.value = false;
    });
};
const findTaskByTab = async (current) => {
  if (activeKey.value == null) {
    formState.creatorId = null;
    formState.userId = null;
    findTask(current);
  } else if (activeKey.value === 2) {
    formState.creatorId = store.getters.userId;
    formState.userId = null;
    findTask(current);
  } else {
    formState.creatorId = null;
    formState.userId = store.getters.userId;
    findTask(current);
  }
};

const fetchCourseList = async () => {
  try {
    console.log('开始获取课程列表');
    const result = await courseDao.getCourseList();
    console.log('课程列表返回结果:', result);
    if (result.data.code === 200) {
      const courses = result.data.data || [];
      store.commit('project/SET_COURSES', courses);
      courseList.value = courses;
      console.log('课程列表已更新:', courses);
    } else {
      console.error('获取课程列表失败:', result.data.msg);
    }
  } catch (error) {
    console.error('获取课程列表异常:', error);
  }
};

const handleOpenCreateTaskModal = async () => {
  await fetchCourseList();
  openCreateTaskModal.value = true;
};
</script>
<style scoped lang="scss">
.container {
  min-width: 960px;
  min-height: 540px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.ant-table-wrapper {
  position: relative;
  height: 100%;
}

.close:hover {
  cursor: pointer;
  color: #6698ff;
}

.show {
  display: none;
}

.priority-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.priority-cell:hover .show {
  display: unset;
}

.pagination-container {
  text-align: center;
  /* 这将使容器内的内容水平居中 */
  margin: 10px 0;
  /* 可选：添加一些顶部间距以分隔表格和分页组件 */
}

.filter {
  margin: 5px 0;
  padding: 0 1%;
  display: flex;
  justify-content: space-between;
}
</style>
